package com.ning.farm_income_back.service;

import com.ning.farm_income_back.domain.Users;
import com.ning.farm_income_back.mapper.UsersMapper;
import com.ning.farm_income_back.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class LoginService {

    @Autowired
    UsersMapper usersMapper;

    public String login(Users user) {
        //判断用户名是否存在,通过用户名查找
        Users u = usersMapper.selectByUsername(user.getUsername());
        if(u == null){
            throw new RuntimeException("该用户不存在");
        }

        if(!u.getPasswordHash().equals(user.getPasswordHash())){
            throw new RuntimeException("密码错误");
        }

        if(!u.getRole().equals(user.getRole())){
            throw new RuntimeException("请选择正确角色");
        }
        //如果一切正确，返回token
        String token = JwtUtils.getToken(u.getRealName());
        return token;
    }
}
